#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
from os import path
from urllib.parse import urlparse
import urllib
import json
import re
import random
from socketserver import ThreadingMixIn
from mysite import urls,settings
from mysite.utils.formatTools import get_app_name
import importlib
sep = '/'
appPath = settings.APP_PATH
installApp = settings.INSTALLED_APP
codeErr = settings.CODE_ERROR
codeScene = settings.CODE_SCENE
# MIME-TYPE
mimedic = [
                        ('.html', 'text/html'),
                        ('.htm', 'text/html'),
                        ('.js', 'application/javascript'),
                        ('.css', 'text/css'),
                        ('.json', 'application/json'),
                        ('.png', 'image/png'),
                        ('.jpg', 'image/jpeg'),
                        ('.gif', 'image/gif'),
                        ('.txt', 'text/plain'),
                        ('.avi', 'video/x-msvideo'),
                        ('.ttf', 'image/ttf'),
                        ('.woff', 'image/woff'),
                        ('.woff2', 'image/woff2'),
                        ('.ico', 'image/ico'),

                    ]

COUNTS = 0
class testHTTPServer_RequestHandler(BaseHTTPRequestHandler):
    response = {
        'code': 0,
        'msg':'',
        'data':{}
    }
    # GET
    def do_GET(self):
        querypath = urlparse(self.path)
        filepath, query = querypath.path, querypath.query
        if "cvedb" in filepath:
            self.cvedb_router_get(filepath)
        else:
            self.match_router_get(filepath,query)
    # POST
    def do_POST(self):
        datas = self.rfile.read(int(self.headers['content-length']))
        isJson = self.is_josn(str(datas,encoding='utf-8'))
        if isJson:
            jsonParam = json.loads(datas)
            self.match_router_post(self.path,jsonParam)
        else:
            params = urllib.parse.parse_qs(str(datas,encoding='utf-8'))
            self.match_router_post(self.path,params)
            #self.send_json_fail(codeErr['5'],"参数错误!")
    def set_json_header(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin','*')#允许跨域
        self.end_headers()
    def get_byte_resp(self,resp:str):
        return resp.encode()
    def match_router_get(self,path,params):
        err = True
        for p in urls.get_url.keys():
            if p == path:
                appName = get_app_name(path.split("/"))
                for a in installApp:
                    if appName == a:
                        apis,func = urls.get_url[path].split("&")
                        app = appPath+"."+appName+"."+apis
                        appApi = importlib.import_module(app)
                        appFunc = getattr(appApi,func)
                        appFunc(self,params)
                        err = False
        if path == "/":
            print("请求路径: " + path)
            if params:
                print("请求参数: " + params)
        elif path.find(".ico") >=0:
            print("请求内容: " + path +" 不存在!")
        else:
            if err:
                self.send_json_fail(codeErr['1'],"请求不存在!")
    def cvedb_router_get(self,path):
        err = True
        appName = "cvedb"
        for a in installApp:
            if appName == a:
                apis,func = urls.get_url["/cvedb"].split("&")
                app = appPath+"."+appName+"."+apis
                appApi = importlib.import_module(app)
                appFunc = getattr(appApi,func)
                appFunc(self,path)

    def match_router_post(self,path,params):
        err = True
        print(path)
        for p in urls.post_url.keys():
            if p == path:
                appName = get_app_name(path.split("/"))
                for a in installApp:
                    if appName == a:
                        apis,func = urls.post_url[path].split("&")
                        app = appPath+"."+appName+"."+apis
                        appApi = importlib.import_module(app)
                        appFunc = getattr(appApi,func)
                        appFunc(self,params)
                        err = False
        if err:
            self.send_json_fail(codeErr['1'],"请求不存在! 请求路径: " + path)
    def is_josn(self,data):
        try:
            json.loads(data)
        except ValueError:
            return False
        return True        
    def send_json_success(self,data:dict):
        self.response['code'] = 0
        self.response['msg'] = ''
        self.response['data'] = data
        self.set_json_header()
        resp = self.get_byte_resp(json.dumps(self.response))
        self.wfile.write(resp)
    def send_file_success(self,data:str):
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.send_header('Access-Control-Allow-Origin','*')#允许跨域
        self.end_headers()  
        resp = self.get_byte_resp(data)
        self.wfile.write(resp)
    def send_html_success(self,data):
        self.send_response(200)
        self.send_header('Content-type', 'text/html; charset=utf-8')
        self.send_header('Access-Control-Allow-Origin','*')#允许跨域
        self.end_headers()  
        resp = data
        self.wfile.write(resp)
    def send_cve_success(self,data):
        self.send_response(200)
        self.send_header('Content-type', 'application/octet-stream')
        self.send_header('Access-Control-Allow-Origin','*')#允许跨域
        self.end_headers()  
        resp = data
        self.wfile.write(resp)           

    def send_json_fail(self,code,msg):
        self.response['code'] = code
        self.response['msg'] = msg
        self.response['data'] = {}
        self.set_json_header()
        resp = self.get_byte_resp(json.dumps(self.response))
        self.wfile.write(resp)

class ThreadingHttpServer(ThreadingMixIn,HTTPServer):
    pass
def run():
    port = 9090
    print('服务启动, 监听端口:', port)
    # Server settings
    server_address = ('', port)
    #httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
    httpd = ThreadingHttpServer(server_address,testHTTPServer_RequestHandler)
    print('HTTP服务运行...')
    httpd.serve_forever()

if __name__ == '__main__':
    run()